package com.vip.jwt.config;

import com.vip.jwt.common.exception.ExceptionEnum;
import com.vip.jwt.common.exception.MyException;
import com.vip.jwt.common.utils.JwtUtil;
import com.vip.jwt.entity.Role;
import com.vip.jwt.entity.User;
import com.vip.jwt.service.RolePermissionService;
import com.vip.jwt.service.UserRoleService;
import com.vip.jwt.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.Permission;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class MyRealm extends AuthorizingRealm {

    @Resource
    private UserService userService;

    @Resource
    private UserRoleService userRoleService;

    @Resource
    private RolePermissionService rolePermissionService;

    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String token = principalCollection.toString();
        String username = JwtUtil.getUsername(token);
        User user = userService.findByUsername(username);
        String userId = user.getId();
        List<Role> roles = userRoleService.findByUserId(userId);
        List<String> roleStrs = roles.stream()
                .map(Role::getCode)
                .collect(Collectors.toList());
        List<String> allPermissionStrs = new ArrayList<>();
        for(int i=0;i<roles.size();i++){
            Role role = roles.get(i);
            String roleId = role.getId();
            List<String> strings = rolePermissionService.findByRoleId(roleId);
            allPermissionStrs.addAll(strings);
        }
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addRoles(roleStrs);
        simpleAuthorizationInfo.addStringPermissions(allPermissionStrs);
        return simpleAuthorizationInfo;
    }

    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String username = (String)authenticationToken.getPrincipal();
        String password = String.valueOf((char[])authenticationToken.getCredentials());
        User user = userService.findByUsername(username);
        if(null==user){
            throw new UnknownAccountException("账号不存在");
        }
        String salt = user.getSalt();
        String findPassword = user.getPassword();
        String hashPassword = User.encryptPassword(password,salt);
        if(!findPassword.equals(hashPassword)){
            throw new IncorrectCredentialsException("密码错误");
        }
        return new SimpleAuthenticationInfo(user,hashPassword, ByteSource.Util.bytes(salt),getName());
    }

}
